package com.cg.service.Impl;

import com.cg.entity.City;
import com.cg.mapper.CityMapper;
import com.cg.result.CityVO;
import com.cg.result.R;
import com.cg.service.CityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 基础表-省市区 服务实现类
 * </p>
 *
 * @author lhy
 * @since 2024-12-26
 */
@Service
public class CityServiceImpl extends ServiceImpl<CityMapper, City> implements CityService {
    @Resource
    private CityMapper cityMapper;
    @Override
    public R<List<CityVO>> search() {
        List<CityVO> cityHierarchies = cityMapper.selectAllCities();
        if (cityHierarchies == null || cityHierarchies.isEmpty()) {
            return R.Success(new ArrayList<>());
        }
        // 使用 Map 来存储每个层级的节点
        Map<Integer, List<CityVO>> citiesByLevel = new HashMap<>();
        for (CityVO city : cityHierarchies) {
            citiesByLevel.computeIfAbsent(city.getLevel(), k -> new ArrayList<>()).add(city);
        }
        // 构建树形结构
        List<CityVO> rootNodes = new ArrayList<>();
        for (CityVO province : citiesByLevel.getOrDefault(1, Collections.emptyList())) {
            rootNodes.add(province);
            addChildren(province, citiesByLevel);
        }
        return R.Success(rootNodes);
    }
    private void addChildren(CityVO parentNode, Map<Integer, List<CityVO>> citiesByLevel) {
        int nextLevel = parentNode.getLevel() + 1;
        if (citiesByLevel.containsKey(nextLevel)) {
            List<CityVO> children = citiesByLevel.get(nextLevel).stream()
                    .filter(city -> Objects.equals(city.getParentId(), parentNode.getId()))
                    .peek(child -> addChildren(child, citiesByLevel))
                    .toList();
            if (!children.isEmpty()) {
                parentNode.setChildren(children);
            }
        }
    }
}


